package com.itany.boot.nmms.service.impl;

import com.itany.boot.nmms.constant.StatusConstant;
import com.itany.boot.nmms.dao.StaffMapper;
import com.itany.boot.nmms.entity.Staff;
import com.itany.boot.nmms.entity.StaffExample;
import com.itany.boot.nmms.exception.*;
import com.itany.boot.nmms.service.StaffService;
import com.itany.boot.nmms.util.MD5Util;
import com.itany.boot.nmms.util.ParamsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class StaffServiceImpl implements StaffService {
    @Autowired
    private StaffMapper staffMapper;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public Staff checkUsernameAndPassword(String loginName, String password, String code, String role, HttpSession session) throws RequestParamsException, VerificationCodeException, StaffNotExistException, MD5Exception, SelectIdentityException {

        if (ParamsUtil.isNull(loginName) || ParamsUtil.isNull(password) || ParamsUtil.isNull(code)) {
            throw new RequestParamsException("请求参数异常:(");
        }

        if ("-1".equals(role)) {
            throw new SelectIdentityException("请选择身份:)");
        }

        String machineCode = (String) session.getAttribute("code");
        System.out.println("code:" + code.equalsIgnoreCase(machineCode));
        if (!code.equalsIgnoreCase(machineCode)) {
            throw new VerificationCodeException("验证码错误:(");
        }

        StaffExample example = new StaffExample();
        example.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password))
                .andIsValidEqualTo(StatusConstant.STAFF_IS_VALID_ENABLE);
        List<Staff> staffList = staffMapper.selectByExample(example);
        if (staffList.isEmpty()) {
            throw new StaffNotExistException("用户名或密码错误:(");
        }

        return staffList.isEmpty()? null:staffList.get(0);
    }
}
